﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BL.Abstract;
using BL.Class;
using BL.Generic;
using DAL.Abstract;
using DAL.Repositories;
using InventizerWEB.GenericObjects;
using PagedList;

namespace InventizerWEB.Controllers
{
    [Authorize]
    public class LABELSController : Controller
    {
        private readonly ILabelBL labelBL;
        private readonly ISecurityHelper securityHelper;

        public LABELSController()
        {
            securityHelper = new SecurityHelper();
            labelBL = new LabelBL();
        }

        public ActionResult Index(int? page)
        {
            try
            {
                if (!securityHelper.CheckIfUserIsAdmin(User.Identity.Name))
                {
                    return RedirectToAction("Fobridden", "Error");
                }
                if (ApplicationSettings.InventoryId == null)
                {
                    return RedirectToAction("Default", "Inventory");
                }
                var pageNumber = (page ?? 1);
                var res = labelBL.GetAllLabels(pageNumber, ApplicationSettings.PaginationCount);
                if (res.BlAnswer == Answer.Success)
                {
                    return View(res.ObjectAnswer.OrderBy(i => i.LABELIDNUMBER)
                        .ToPagedList(pageNumber, ApplicationSettings.pageSize));
                }
                return RedirectToAction("Error", "Error");
            }
            catch (Exception ex)
            {
                TempData["Error"] = "Wystąpił błąd: " + ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        public ActionResult Load()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Load(HttpPostedFileBase file, FormCollection collection)
        {
            try
            {
                var separator = collection["separator"];
                if (file != null && file.ContentLength > 0)
                {
                    string newFileName = "LABELS_" + Guid.NewGuid() + ".txt";
                    string filePath = Path.Combine(Server.MapPath("~/LoadedFiles"), newFileName);
                    file.SaveAs(filePath);
                    labelBL.SaveFileToServerAndProcess(filePath, ApplicationSettings.InventoryIdInt, separator);
                }
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                TempData["Error"] = "Blad ladowania pliku: " + ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }
    }
}